//
//  WQPhotosBrowserAnimator.swift
//  sanwuWeibo
//
//  Created by 王先强 on 15/12/20.
//  Copyright © 2015年 王先强. All rights reserved.
//

import UIKit

///  present动画的协议
protocol WQPhotosBrowserAnimatorPresentDelegate: NSObjectProtocol {
    ///  参与展现动画的图像视图
    ///
    ///  - parameter indexPath: 图像视图对应的indexPath
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView
    ///  参与展现动画的图像视图 起始rect
    ///
    ///  - parameter indexPath: 图像视图对应的indexPath
    func photoBrowserPresentFromRect(indexPath: NSIndexPath) -> CGRect
    ///  参与展现动画的图像视图 最终rect
    ///
    ///  - parameter indexPath: 图像视图对应的indexPath
    func photoBrowserPresetnToRect(indexPath: NSIndexPath) -> CGRect
}
///  dismiss动画的协议
protocol WQPhotosBrowserAnimatorDismissDelegate: NSObjectProtocol {
    //获取解除转场动画的图像视图
    func imageViewForDismiss() -> UIImageView
    // 获取解除转场动画的图像索引
    func indexPathForDismiss() -> NSIndexPath
}



//提供转场动画的代理对象
class WQPhotosBrowserAnimator: NSObject,UIViewControllerTransitioningDelegate {

    // 定义是present动画标记
    var isPresent: Bool = true
    //定义代理present
    weak var presentDelegate: WQPhotosBrowserAnimatorPresentDelegate?
    //定义代理dismiss
    weak var dismissDelegate: WQPhotosBrowserAnimatorDismissDelegate?
    //定义索引
    var indexPath: NSIndexPath?
    
    // 设置代理参数函数
    func setDelegatePramas(presentDelegate: WQPhotosBrowserAnimatorPresentDelegate, dismissDelegate: WQPhotosBrowserAnimatorDismissDelegate, indexPath: NSIndexPath) {
        self.presentDelegate = presentDelegate
        self.dismissDelegate = dismissDelegate
        self.indexPath = indexPath
    }
    
    // 提供转场动画Present 的对象 必须遵守UIViewControllerAnimatedTransitioning 协议
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = true
        return self
    }

    // 提供转场动画Dismiss 的对象 必须遵守UIViewControllerAnimatedTransitioning 协议
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = false
        return self
    }
    
}


extension WQPhotosBrowserAnimator: UIViewControllerAnimatedTransitioning {
    //转场动画时间
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
    /// 实现具体的动画效果 - 一旦实现了此方法，所有的动画代码都交由程序员负责
    ///
    /// - parameter transitionContext: 转场动画的上下文 － 提供动画所需要的素材
    /**
    1. 容器视图 － 会将 Modal 要展现的视图包装在容器视图中
    存放的视图要显示－必须自己指定大小！不会通过自动布局填满屏幕
    2. viewControllerForKey: fromVC / toVC
    3. viewForKey: fromView / toView
    4. completeTransition: 无论转场是否被取消，都必须调用
    否则，系统不做其他事件处理！
    */
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        // 转场动画的来源，目标控制器或者view
        /**
        let fromVc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
        let toVc = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
        let fromView = transitionContext.viewControllerForKey(UITransitionContextFromViewKey)
        let toView = transitionContext.viewControllerForKey(UITransitionContextToViewKey)
        */
        self.isPresent ? presentController(transitionContext) : dismissController(transitionContext)
    }
    
    
    private func presentController(transitionContext: UIViewControllerContextTransitioning) {
        //获取目标view
       let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
        //把view加到containerView中
        transitionContext.containerView()?.addSubview(toView)
        toView.alpha = 0
        
        // 获取图片view
        guard let presentImageView = presentDelegate?.imageViewForPresent(indexPath!) else {
            transitionContext.completeTransition(true)
            return
        }
        guard let startRect = presentDelegate?.photoBrowserPresentFromRect(indexPath!) else {
            transitionContext.completeTransition(true)
            return
        }
        guard let endRect = presentDelegate?.photoBrowserPresetnToRect(indexPath!) else {
            transitionContext.completeTransition(true)
            return
        }
        
        transitionContext.containerView()?.addSubview(presentImageView)
        presentImageView.frame = startRect
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            toView.alpha = 1
            presentImageView.alpha = 0
            presentImageView.frame = endRect
            }) { (_) -> Void in
                //完成告诉系统动画完成
                presentImageView.removeFromSuperview()
                transitionContext.completeTransition(true)
        }
        
    }
    private func dismissController(transitionContext: UIViewControllerContextTransitioning) {
        let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
        fromView?.removeFromSuperview()
        guard let dismissImageView = dismissDelegate?.imageViewForDismiss() else {
            transitionContext.completeTransition(true)
            return
        }
        guard let indexPathForEnd = dismissDelegate?.indexPathForDismiss() else {
            transitionContext.completeTransition(true)
            return
        }
        guard let endRect = presentDelegate?.photoBrowserPresentFromRect(indexPathForEnd) else {
            transitionContext.completeTransition(true)
            return
        }
//        print(dismissImageView.frame)
        transitionContext.containerView()?.addSubview(dismissImageView)
//        print(endRect)
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            dismissImageView.frame = endRect
            dismissImageView.alpha = 0
            }) { (_) -> Void in
                transitionContext.completeTransition(true)
        }
    }
}